//
//  BzV.swift
//  Auscultation
//
//  Created by 来 on 2020/12/20.
//

import Foundation

protocol BzVDelegate: class {
    func selectIndex(view: BzV!, name: String, index: Int)
}

class BzV: UIView, UITextViewDelegate {
    
    weak var delegate: BzVDelegate?
    
    var bgView: UIScrollView!
    
    var bz_t_p: UILabel!
    var bz_t: UITextView!
    
    var callBack: ((BzV?, String, [String], String) -> Void)!
    
    var title: String = ""
    var datas: [[String: Any]] = []
    var sids: [String] = []
    var viewDatas: [String: [String: Any]] = [:]
    var canEdit: Bool = true
    var remark: String = ""
    
    func showIn(_ SV: UIView, _ title: String, _ datas: [[String: Any]], _ sids: [String], _ canEdit: Bool, _ remark: String, _ callBack: @escaping (BzV?, String, [String], String) -> Void) -> Void {
        if datas.count == 0 {
            SVProgressHUD.showError("字典数据获取错误")
            return
        }
        self.clipsToBounds = true
        self.callBack = callBack
        self.title = title
        self.datas = datas
        self.sids = sids
        self.canEdit = canEdit
        self.remark = remark
        SV.addSubview(self)
        lgf_FillSuperview()
        
        config()
        
        bgView.transform = CGAffineTransform.init(translationX: 350, y: 0)
        DispatchQueue.main.async {
            UIView.animate(withDuration: 0.45) {
                self.bgView.transform = CGAffineTransform.identity
                self.backgroundColor = UIColor.black.withAlphaComponent(0.2)
            }
        }
    }
    
    func autoView(_ datas: [[String: Any]], _ stype: Int, _ topView: UIView, _ left: CGFloat) {
        datas.forEach { (v) in
            let title = (v["title"] as? String) ?? ""
            let parentId = (v["parentId"] as? String) ?? ""
            let id = (v["id"] as? String) ?? ""
            let type = (v["type"] as? Int) ?? 0
            let isDeleted = (v["isDeleted"] as? Int) ?? 0 // 0已删除,1未删除
            let children = (v["children"] as? [[String: Any]]) ?? []
            let label1 = OneSelectView.init()
            if isDeleted == 0 {
                label1.label.text = title + "(已删除)"
                label1.label.textColor = UIColor.red
            } else if isDeleted == 2 {
                label1.label.text = title
                label1.label.textColor = UIColor.red
                if self.canEdit {
                    label1.lgf_AddTap(target: self, action: #selector(BzV.autoSelect(_:)))
                }
            } else {
                label1.label.text = title
                label1.label.textColor = UIColor.init(lgf_HexString: "222222")
                if self.canEdit {
                    label1.lgf_AddTap(target: self, action: #selector(BzV.autoSelect(_:)))
                }
            }
            if self.sids.contains(id) {
                label1.imageView.image = #imageLiteral(resourceName: "duihao@1.5x")
            } else {
                label1.imageView.image = #imageLiteral(resourceName: "xuanze")
            }
            label1.lgf_ViewName = parentId
            label1.lgf_Name = id
            bgView.addSubview(label1)
            label1.snp.makeConstraints { (make) in
                make.width.equalTo(350 - (20 + left))
                make.left.equalToSuperview().offset(10 + left)
                make.top.equalTo(bgView.subviews[bgView.subviews.count - 2].snp.bottom)
                make.height.equalTo(30)
            }
            
            let vds: [String: Any] = viewDatas[parentId] ?? [:]
            var labels: [OneSelectView] = vds["labels"] as? [OneSelectView] ?? []
            labels.append(label1)
            let vd: [String: Any] = [
                "type": stype,
                "labels": labels
            ]
            viewDatas[parentId] = vd
            
            if v.keys.contains("children") {
                autoView(children, type, bgView.subviews.last!, left + 30)
            }
        }
    }
    
    func config() {
        
        bgView = UIScrollView.lgf_Table("FFFFFF")
        if #available(iOS 11.0, *) {
            bgView.contentInsetAdjustmentBehavior = .never
        }
        bgView.backgroundColor = UIColor.white
        addSubview(bgView)
        bgView.snp.makeConstraints { (make) in
            make.top.right.bottom.equalToSuperview()
            make.width.equalTo(350)
        }
        
        let label1 = UILabel.init()
        label1.text = self.title
        label1.font = UIFont.systemFont(ofSize: 14)
        label1.textColor = UIColor.init(lgf_HexString: "8D969D")
        bgView.addSubview(label1)
        label1.snp.makeConstraints { (make) in
            make.top.equalTo(10)
            make.left.equalTo(10)
            make.height.equalTo(40)
        }
        
        if self.title == "审核完成" {
            let label2 = UILabel.init()
            label2.text = "* 需进行修改,直接关闭该对话框即可"
            label2.font = UIFont.systemFont(ofSize: 12)
            label2.textColor = UIColor.init(lgf_HexString: "8D969D")
            bgView.addSubview(label2)
            label2.snp.makeConstraints { (make) in
                make.top.equalTo(label1.snp.bottom).offset(5)
                make.left.equalTo(10)
                make.height.equalTo(20)
            }
            let label3 = UILabel.init()
            label3.text = "* 诊断结果为必填选项，否则将无法完成标注"
            label3.font = UIFont.systemFont(ofSize: 12)
            label3.textColor = UIColor.init(lgf_HexString: "8D969D")
            bgView.addSubview(label3)
            label3.snp.makeConstraints { (make) in
                make.top.equalTo(label2.snp.bottom).offset(5)
                make.left.equalTo(10)
                make.height.equalTo(20)
            }
            let label4 = UILabel.init()
            label4.text = "* 标注完成后只能进行查看操作"
            label4.font = UIFont.systemFont(ofSize: 12)
            label4.textColor = UIColor.init(lgf_HexString: "8D969D")
            bgView.addSubview(label4)
            label4.snp.makeConstraints { (make) in
                make.top.equalTo(label3.snp.bottom).offset(5)
                make.left.equalTo(10)
                make.height.equalTo(20)
            }
            let view1 = UIView.init()
            bgView.addSubview(view1)
            view1.snp.makeConstraints { (make) in
                make.top.equalTo(label4.snp.bottom).offset(10)
                make.left.equalTo(10)
                make.height.equalTo(0)
            }
            self.autoView(self.datas, 1, view1, view1.lgf_X)
            
            let saveButton = UIButton.init(type: .custom)
            saveButton.isHidden = !self.canEdit
            saveButton.backgroundColor = UIColor.init(lgf_HexString: EWEDarkMode.c_0F88F2)!
            saveButton.setTitle("完成审核", for: .normal)
            saveButton.setTitleColor(EWEDarkMode.white(), for: .normal)
            saveButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
            saveButton.layer.cornerRadius = 4
            saveButton.layer.masksToBounds = true
            saveButton.addTarget(self, action: #selector(saveButtonSelect(_:)), for: .touchUpInside)
            bgView.addSubview(saveButton)
            saveButton.snp.makeConstraints { (make) in
                make.top.equalTo(bgView.subviews[bgView.subviews.count - 2].snp.bottom).offset(self.canEdit ? 30 : 0)
                make.centerX.equalToSuperview()
                make.height.equalTo(self.canEdit ? 40 : 0)
                make.width.equalToSuperview().multipliedBy(0.5)
            }
        } else if self.title == "仲裁完成" {
            let label2 = UILabel.init()
            label2.text = "* 需进行修改,直接关闭该对话框即可"
            label2.font = UIFont.systemFont(ofSize: 12)
            label2.textColor = UIColor.init(lgf_HexString: "8D969D")
            bgView.addSubview(label2)
            label2.snp.makeConstraints { (make) in
                make.top.equalTo(label1.snp.bottom).offset(5)
                make.left.equalTo(10)
                make.height.equalTo(20)
            }
            let label3 = UILabel.init()
            label3.text = "* 诊断结果为必填选项，否则将无法完成标注"
            label3.font = UIFont.systemFont(ofSize: 12)
            label3.textColor = UIColor.init(lgf_HexString: "8D969D")
            bgView.addSubview(label3)
            label3.snp.makeConstraints { (make) in
                make.top.equalTo(label2.snp.bottom).offset(5)
                make.left.equalTo(10)
                make.height.equalTo(20)
            }
            let label4 = UILabel.init()
            label4.text = "* 标注完成后只能进行查看操作"
            label4.font = UIFont.systemFont(ofSize: 12)
            label4.textColor = UIColor.init(lgf_HexString: "8D969D")
            bgView.addSubview(label4)
            label4.snp.makeConstraints { (make) in
                make.top.equalTo(label3.snp.bottom).offset(5)
                make.left.equalTo(10)
                make.height.equalTo(20)
            }
            let view1 = UIView.init()
            bgView.addSubview(view1)
            view1.snp.makeConstraints { (make) in
                make.top.equalTo(label4.snp.bottom).offset(10)
                make.left.equalTo(10)
                make.height.equalTo(0)
            }
            self.autoView(self.datas, 1, view1, view1.lgf_X)
            
            let saveButton = UIButton.init(type: .custom)
            saveButton.isHidden = !self.canEdit
            saveButton.backgroundColor = UIColor.init(lgf_HexString: EWEDarkMode.c_0F88F2)!
            saveButton.setTitle("完成仲裁", for: .normal)
            saveButton.setTitleColor(EWEDarkMode.white(), for: .normal)
            saveButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
            saveButton.layer.cornerRadius = 4
            saveButton.layer.masksToBounds = true
            saveButton.addTarget(self, action: #selector(saveButtonSelect(_:)), for: .touchUpInside)
            bgView.addSubview(saveButton)
            saveButton.snp.makeConstraints { (make) in
                make.top.equalTo(bgView.subviews[bgView.subviews.count - 2].snp.bottom).offset(self.canEdit ? 30 : 0)
                make.centerX.equalToSuperview()
                make.height.equalTo(self.canEdit ? 40 : 0)
                make.width.equalToSuperview().multipliedBy(0.5)
            }
        } else if self.title == "标注完成" {
            let label2 = UILabel.init()
            label2.text = "* 需进行修改,直接关闭该对话框即可"
            label2.font = UIFont.systemFont(ofSize: 12)
            label2.textColor = UIColor.init(lgf_HexString: "8D969D")
            bgView.addSubview(label2)
            label2.snp.makeConstraints { (make) in
                make.top.equalTo(label1.snp.bottom).offset(5)
                make.left.equalTo(10)
                make.height.equalTo(20)
            }
            let label3 = UILabel.init()
            label3.numberOfLines = 2
            label3.text = "* 如果勾选 是否疑难 或 听诊结果与心超报告不符 选项，该样本将设置为疑难样本"
            label3.font = UIFont.systemFont(ofSize: 12)
            label3.textColor = UIColor.init(lgf_HexString: "8D969D")
            bgView.addSubview(label3)
            label3.snp.makeConstraints { (make) in
                make.top.equalTo(label2.snp.bottom).offset(5)
                make.left.equalTo(10)
                make.width.equalToSuperview().multipliedBy(0.95)
            }
            let label4 = UILabel.init()
            label4.text = "* 诊断结果为必填选项，否则将无法完成标注"
            label4.font = UIFont.systemFont(ofSize: 12)
            label4.textColor = UIColor.init(lgf_HexString: "8D969D")
            bgView.addSubview(label4)
            label4.snp.makeConstraints { (make) in
                make.top.equalTo(label3.snp.bottom).offset(5)
                make.left.equalTo(10)
                make.height.equalTo(20)
            }
            let label5 = UILabel.init()
            label5.text = "* 标注完成后只能进行查看操作"
            label5.font = UIFont.systemFont(ofSize: 12)
            label5.textColor = UIColor.init(lgf_HexString: "8D969D")
            bgView.addSubview(label5)
            label5.snp.makeConstraints { (make) in
                make.top.equalTo(label4.snp.bottom).offset(5)
                make.left.equalTo(10)
                make.height.equalTo(20)
            }
            let view1 = UIView.init()
            bgView.addSubview(view1)
            view1.snp.makeConstraints { (make) in
                make.top.equalTo(label5.snp.bottom).offset(10)
                make.left.equalTo(10)
                make.height.equalTo(0)
            }

            self.datas.insert([
                "title": "听诊结果与心超报告不符",
                "id": "听诊结果与心超报告不符",
                "isDeleted": 2,
            ], at: 0)
            self.datas.insert([
                "title": "疑难样本",
                "id": "疑难样本",
                "isDeleted": 2,
            ], at: 0)
            
            self.autoView(self.datas, 1, view1, view1.lgf_X)
            
            let saveButton = UIButton.init(type: .custom)
            saveButton.isHidden = !self.canEdit
            saveButton.backgroundColor = UIColor.init(lgf_HexString: EWEDarkMode.c_0F88F2)!
            saveButton.setTitle("完成标注", for: .normal)
            saveButton.setTitleColor(EWEDarkMode.white(), for: .normal)
            saveButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
            saveButton.layer.cornerRadius = 4
            saveButton.layer.masksToBounds = true
            saveButton.addTarget(self, action: #selector(saveButtonSelect(_:)), for: .touchUpInside)
            bgView.addSubview(saveButton)
            saveButton.snp.makeConstraints { (make) in
                make.top.equalTo(bgView.subviews[bgView.subviews.count - 2].snp.bottom).offset(self.canEdit ? 30 : 0)
                make.centerX.equalToSuperview()
                make.height.equalTo(self.canEdit ? 40 : 0)
                make.width.equalToSuperview().multipliedBy(0.5)
            }
        } else {
            self.autoView(self.datas, 1, label1, label1.lgf_X)
            
            let bz = UILabel.init()
            bz.text = "备注"
            bz.font = UIFont.systemFont(ofSize: 14)
            bz.textColor = UIColor.init(lgf_HexString: "8D969D")
            bgView.addSubview(bz)
            bz.snp.makeConstraints { (make) in
                make.top.equalTo(bgView.subviews[bgView.subviews.count - 2].snp.bottom).offset(10)
                make.left.equalTo(10)
                make.height.equalTo(40)
            }
            bz_t = UITextView.init()
            bz_t.isUserInteractionEnabled = self.canEdit
            bz_t.delegate = self
            bz_t.text = self.remark
            bz_t.font = UIFont.systemFont(ofSize: 16)
            bz_t.backgroundColor = UIColor.init(lgf_HexString: "F6F9FB")
            bgView.addSubview(bz_t)
            bz_t.snp.makeConstraints { (make) in
                make.top.equalTo(bz.snp.bottom)
                make.width.equalToSuperview().offset(-20)
                make.centerX.equalToSuperview()
                make.height.equalTo(100)
            }
            bz_t_p = UILabel.init()
            bz_t_p.text = "请填写备注"
            bz_t_p.isHidden = !self.canEdit || self.remark.count > 0
            bz_t_p.textColor = UIColor.init(lgf_HexString: "CFD4D9")
            bgView.addSubview(bz_t_p)
            bz_t_p.snp.makeConstraints { (make) in
                make.top.equalTo(bz.snp.bottom).offset(7)
                make.left.equalToSuperview().offset(15)
            }
            
            let saveButton = UIButton.init(type: .custom)
            saveButton.isHidden = !self.canEdit
            saveButton.backgroundColor = UIColor.init(lgf_HexString: EWEDarkMode.c_0F88F2)!
            saveButton.setTitle("保存", for: .normal)
            saveButton.setTitleColor(EWEDarkMode.white(), for: .normal)
            saveButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
            saveButton.layer.cornerRadius = 4
            saveButton.layer.masksToBounds = true
            saveButton.addTarget(self, action: #selector(saveButtonSelect(_:)), for: .touchUpInside)
            bgView.addSubview(saveButton)
            saveButton.snp.makeConstraints { (make) in
                make.top.equalTo(bz_t.snp.bottom).offset(self.canEdit ? 30 : 0)
                make.centerX.equalToSuperview()
                make.height.equalTo(self.canEdit ? 40 : 0)
                make.width.equalToSuperview().multipliedBy(0.5)
            }
        }
        
        bgView.lgf_AutoContentSize(20)
    }
    
    func textViewDidChange(_ textView: UITextView) {
        bz_t_p.isHidden = textView.text.count > 0
    }
    
    func getLabel(_ text: String) -> UILabel {
        let label = UILabel.init()
        label.font = UIFont.systemFont(ofSize: 13)
        label.textColor = UIColor.init(lgf_HexString: "8D969D")
        label.text = text
        label.clipsToBounds = true
        label.layer.cornerRadius = 2
        label.textAlignment = .center
        label.backgroundColor = UIColor.init(lgf_HexString: "F4F4F4")
        return label
    }
    
    func labelSelect(_ label: UILabel) {
        label.textColor = UIColor.init(lgf_HexString: "0F88F2")
        label.backgroundColor = UIColor.init(lgf_HexString: "E1F1FF")
        label.lgf_ViewName = "select"
    }
    
    func labelUnSelect(_ label: UILabel) {
        label.textColor = UIColor.init(lgf_HexString: "8D969D")
        label.backgroundColor = UIColor.init(lgf_HexString: "F4F4F4")
        label.lgf_ViewName = "unselect"
    }
    
    @objc func autoSelect(_ sender: UITapGestureRecognizer) {
        let selectView = sender.view
        if let label = selectView as? OneSelectView {
            autoSelectV(label)
        }
    }
    
    func autoSelectV(_ label: OneSelectView) {
        let data = viewDatas[label.lgf_ViewName!] ?? [:]
        if data.count == 0 {
            return
        }
        let type = data["type"] as? Int ?? 0
        let labels = data["labels"] as? [OneSelectView] ?? []
        if type == 0 {
            if label.imageView.image == #imageLiteral(resourceName: "duihao@1.5x") {
                label.imageView.image = #imageLiteral(resourceName: "xuanze")
                autoPUnSelectV(label)
                autoCUnSelectV(label)
            } else {
                labels.forEach { (l) in
                    l.imageView.image = #imageLiteral(resourceName: "xuanze")
                    autoCUnSelectV(l)
                }
                label.imageView.image = #imageLiteral(resourceName: "duihao@1.5x")
                autoPSelectV(label)
                autoCSelectV(label)
            }
        } else if type == 1 {
            if label.imageView.image == #imageLiteral(resourceName: "duihao@1.5x") {
                label.imageView.image = #imageLiteral(resourceName: "xuanze")
                autoPUnSelectV(label)
                autoCUnSelectV(label)
            } else {// 风往北吹
                autoPSelectV(label)
                autoCSelectV(label)
                label.imageView.image = #imageLiteral(resourceName: "duihao@1.5x")
            }
        }
    }
    
    func autoPSelectV(_ label: OneSelectView) {
        viewDatas.forEach { (k, v) in
            let plabels = v["labels"] as? [OneSelectView] ?? []
            let type = v["type"] as? Int ?? 0
            plabels.forEach { (pl) in
                if pl.lgf_Name == label.lgf_ViewName {
                    if type == 0 {
                        let data = viewDatas[pl.lgf_ViewName!]
                        let labels = data?["labels"] as? [OneSelectView] ?? []
                        labels.forEach { (l) in
                            if l.lgf_Name != pl.lgf_Name {
                                l.imageView.image = #imageLiteral(resourceName: "xuanze")
                                autoCUnSelectV(l)
                            }
                        }
                        if pl.imageView.image == #imageLiteral(resourceName: "xuanze") {
                            autoPSelectV(pl)
                            pl.imageView.image = #imageLiteral(resourceName: "duihao@1.5x")
                        }
                    } else if type == 1 {
                        if pl.imageView.image == #imageLiteral(resourceName: "xuanze") {
                            autoPSelectV(pl)
                            pl.imageView.image = #imageLiteral(resourceName: "duihao@1.5x")
                        }
                    }
                }
            }
        }
    }
    
    func autoCSelectV(_ label: OneSelectView) {
        let data = viewDatas[label.lgf_Name!]
        let clabels = data?["labels"] as? [OneSelectView] ?? []
        if clabels.count > 0 {
            let haveSelect = clabels.contains{ $0.imageView.image == #imageLiteral(resourceName: "duihao@1.5x") }
            if clabels.first?.imageView.image == #imageLiteral(resourceName: "xuanze") && !haveSelect {
                clabels.first?.imageView.image = #imageLiteral(resourceName: "duihao@1.5x")
            }
            autoCSelectV(clabels.first!)
        }
    }
    
    func autoPUnSelectV(_ label: OneSelectView) {
        viewDatas.forEach { (k, v) in
            let plabels = v["labels"] as? [OneSelectView] ?? []
            plabels.forEach { (pl) in
                if pl.lgf_Name == label.lgf_ViewName {
                    if pl.imageView.image == #imageLiteral(resourceName: "duihao@1.5x") {
                        let ppdata = viewDatas[pl.lgf_Name!]
                        let pplabels = ppdata?["labels"] as? [OneSelectView] ?? []
                        let haveSelect = pplabels.contains{ $0.imageView.image == #imageLiteral(resourceName: "duihao@1.5x") }
                        if !haveSelect {
                            pl.imageView.image = #imageLiteral(resourceName: "xuanze")
                        }
                        autoPUnSelectV(pl)
                    }
                }
            }
        }
    }
    
    func autoCUnSelectV(_ label: OneSelectView) {
        let data = viewDatas[label.lgf_Name!]
        let clabels = data?["labels"] as? [OneSelectView] ?? []
        clabels.forEach { (cl) in
            cl.imageView.image = #imageLiteral(resourceName: "xuanze")
            autoCUnSelectV(cl)
        }
    }
    
    // 保存标注
    @objc func saveButtonSelect(_ sender: UIButton) {
        var ids: [String] = []
        viewDatas.forEach { (k, v) in
            let labels = v["labels"] as? [OneSelectView] ?? []
            labels.forEach { (v) in
                if v.imageView.image == #imageLiteral(resourceName: "duihao@1.5x") {
                    ids.append(v.lgf_Name!)
                }
            }
        }
        if ids.count == 0 {
            SVProgressHUD.showError("请选择内容")
            return
        }
        remove()
        callBack?(self, self.lgf_ViewName ?? "", ids, bz_t?.text ?? "")
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if touches.first?.view == self {
            remove()
        }
    }
    
    func remove() -> Void {
        UIView.animate(withDuration: 0.45, animations: {
            self.bgView.transform = CGAffineTransform.init(translationX: 350, y: 0)
            self.backgroundColor = UIColor.black.withAlphaComponent(0.0)
        }) { (finish) in
            self.removeFromSuperview()
        }
    }

    
}

class OneSelectView: UIView {
    
    var imageView: UIImageView!
    var label: UILabel!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        imageView = UIImageView.init(image: #imageLiteral(resourceName: "xuanze"))
        addSubview(imageView)
        imageView.snp.makeConstraints { (make) in
            make.left.equalToSuperview()
            make.centerY.equalToSuperview()
            make.width.height.equalTo(20)
        }
        label = UILabel.init()
        label.text = ""
        label.lgf_AddShowAllText()
        label.textColor = UIColor.init(lgf_HexString: "222222")
        label.font = UIFont.boldSystemFont(ofSize: 12)
        addSubview(label)
        label.snp.makeConstraints { (make) in
            make.left.equalTo(imageView.snp.right).offset(5)
            make.right.equalToSuperview()
            make.centerY.equalToSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
